//切换到另一个界面
var web = document.querySelector(".web");
var mian = document.querySelector(".mian");
var start = document.querySelector(".getshow");
var overall = document.querySelector(".overall");
var gamelevel = document.querySelector(".gamelevel");
var startBth = document.querySelector(".overall button");
var gameBth = document.querySelector(".gamelevel button");
startBth.addEventListener("click", ()=>{
	startBth.parentNode.parentNode.style.transform = "translateX(-100%)";
});
gameBth.addEventListener("click", ()=>{
	gameBth.parentNode.style.transform = "translateX(-50%)";
});

function bump(box, show) {
	var boxInfo = box.getBoundingClientRect();
	var showInfo = show.getBoundingClientRect();
	var t1 = boxInfo.top;
	l1 = boxInfo.left;
	r1 = boxInfo.right;
	b1 = boxInfo.bottom;

	var t2 = showInfo.top;
	l2 = showInfo.left;
	r2 = showInfo.right;
	b2 = showInfo.bottom;

	if(r1 < l2 || l1 > r2 || t1 > b2 || b1 < t2) {
		console.log("未出现碰撞");
		return false;
	} else {
		console.log("发出警告:已碰撞！");
		return true;
	}
}

//随机生成圆
function getCircle() {
	var div = document.createElement("div");
	var clientW = overall.clientWidth;
	var clientH = overall.clientHeight;
	//	随机生成圆球的宽高 且直径不小于20
	var divW = divH = Math.floor(Math.random() * 60 + 20);
	//	随机生成top值 和 left值
	var divT = Math.floor(Math.random() * clientH);
	var divL = Math.floor(Math.random() * clientW);

	//	防止超出屏幕  如果超出最大top/left，则让球贴边
	divT > clientH - divH ? divT = clientH - divH : "";
	divL > clientW - divW ? divL = clientW - divW : "";

	div.style.width = `${divW}px`;
	div.style.height = `${divH}px`;
	div.style.top = `${divT}px`;
	div.style.left = `${divL}px`;
	div.style.borderRadius = "50%";
	div.style.backgroundColor = "#FFFFFF";
	div.style.position = "absolute";
	var allBall = document.querySelectorAll(".web div");
	allBall.forEach((e) => {
		e.classList.remove("last");
	})
	div.classList.add("last");
	web.appendChild(div);
	return div;
}
getCircle();

//	每次生成新的圆,检测是否于已有的圆会碰撞,
var firstBall = document.querySelector(".web div");
console.log(firstBall)
firstBall.addEventListener("click", ballEvent);

// 新增球
function ballEvent() {
	if(this.classList.contains("last")) {
		console.log("已经是最后一个球了");
	} else {
		console.log("游戏结束。");
		return
	}
	var allBall = document.querySelectorAll(".web div");
	//	通过 getCircle 的返回值 拿到每次新建出来的圆,为下一步碰撞检测提供检测对象
	var newCircle = getCircle();
	(function check(target) {
		allBall.forEach((e) => {
			//		如果新生成的圆与已有的圆碰撞,则移除并重新创建新圆
			if(bump(e, target)) {
				//		1.先移除
				target.remove();
				//		2.在创建
				var newCircle = getCircle();
				//		3.通过递归传入新创建的圆，重新进行判断
				check(newCircle);
			} else {
				addEvent();
			}
		})
	}(newCircle));
}

//	给每个圆添加点击事件
function addEvent() {
	var allBall = document.querySelectorAll(".web div");
	allBall.forEach((e) => {
		e.addEventListener("click", ballEvent);
	})
}

//  关卡切换

// 动态增加分数
